<template>
  <div>
    <!-- 用户列表表格 -->
    <el-table :data="userList" stripe style="width: 100%">
      <el-table-column prop="username" label="账号" width="150" />
      <el-table-column prop="email" label="邮箱" width="200" />
      <el-table-column prop="followCount" label="关注数" width="100" />
      <el-table-column prop="fanCount" label="粉丝数" width="100" />
      <el-table-column prop="level" label="用户等级" width="100" />
      <el-table-column prop="coins" label="硬币数" width="100" />

      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)" type="primary">修改</el-button>
          <el-button size="mini" @click="openPasswordDialog(scope.row)" type="warning">修改密码</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination v-model:current-page="pagination.page" :page-size="pagination.size" :total="pagination.totalRecords"
      layout="total, prev, pager, next, sizes" @current-change="handlePageChange" @size-change="handleSizeChange"
      style="text-align: right; margin-top: 20px;" />

    <!-- 修改用户信息的对话框 -->
    <el-dialog v-model="isEditDialogVisible" title="修改用户信息" width="400px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="关注数" prop="followCount">
          <el-input-number v-model="editForm.followCount" :min="0" />
        </el-form-item>
        <el-form-item label="粉丝数" prop="fanCount">
          <el-input-number v-model="editForm.fanCount" :min="0" />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-input-number v-model="editForm.level" :min="1" />
        </el-form-item>
        <el-form-item label="硬币数" prop="coins">
          <el-input-number v-model="editForm.coins" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认</el-button>
      </div>
    </el-dialog>

    <!-- 修改用户密码的对话框 -->
    <el-dialog v-model="isPasswordDialogVisible" title="修改用户密码" width="400px">
      <el-form :model="passwordForm" label-width="80px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPasswordUpdate">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const userList = ref([]);
const isEditDialogVisible = ref(false);
const isPasswordDialogVisible = ref(false); // 控制密码对话框的显示

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  totalRecords: 0,
});

// 用户编辑表单
const editForm = reactive({
  id: 0,
  username: '',
  email: '',
  followCount: 0,
  fanCount: 0,
  level: 1,
  coins: 0
});

// 用户密码表单
const passwordForm = reactive({
  id: 0,
  password: ''
});

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await axios.get('/api/manage/user/all', {
      params: { pageNum: pagination.page, pageSize: pagination.size }
    });
    if (response.data.code === 200) {
      userList.value = response.data.data.listData;
      pagination.totalRecords = response.data.data.totalRecords;
    }
  } catch (error) {
    ElMessage.error('获取用户数据失败');
  }
};

// 打开修改用户信息的对话框
const openEditDialog = (user: any) => {
  editForm.id = user.id;
  editForm.username = user.username;
  editForm.email = user.email;
  editForm.followCount = user.followCount;
  editForm.fanCount = user.fanCount;
  editForm.level = user.level;
  editForm.coins = user.coins;
  isEditDialogVisible.value = true;
};

// 打开修改密码的对话框
const openPasswordDialog = (user: any) => {
  passwordForm.id = user.id;
  passwordForm.password = ''; // 清空旧密码
  isPasswordDialogVisible.value = true;
};

// 确认编辑用户信息
const confirmEdit = async () => {
  try {
    const rsp = await axios.put('/api/manage/user', {
      id: editForm.id,
      username: editForm.username,
      email: editForm.email,
      followCount: editForm.followCount,
      fanCount: editForm.fanCount,
      level: editForm.level,
      coins: editForm.coins
    });
    console.log({
      id: editForm.id,
      username: editForm.username,
      email: editForm.email,
      followCount: editForm.followCount,
      fanCount: editForm.fanCount,
      level: editForm.level,
      coins: editForm.coins
    });

    if (rsp.data.code !== 200) {
      console.error('更新失败：', rsp.data);
      ElMessage.error('更新失败');
      return;
    }
    ElMessage.success('用户信息已更新');
    isEditDialogVisible.value = false;
    fetchUsers(); // 更新用户列表
  } catch (error) {
    ElMessage.error('更新用户信息失败');
  }
};

// 确认修改密码
const confirmPasswordUpdate = async () => {
  try {
    const rsp = await axios.put(`/api/manage/user/password?id=${passwordForm.id}&password=${passwordForm.password}`);
    if (rsp.data.code !== 200) {
      console.error('密码更新失败：', rsp.data);
      ElMessage.error('密码更新失败');
      return;
    }
    ElMessage.success('用户密码已更新');
    isPasswordDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('更新用户密码失败');
  }
};

// 删除用户
const deleteUser = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除此用户？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await axios.post('/api/manage/user/delete', { id });
    ElMessage.success('用户已删除');
    fetchUsers(); // 更新用户列表
  } catch (error) {
    ElMessage.error('删除用户失败');
  }
};

// 处理分页页码变化
const handlePageChange = (newPage: number) => {
  pagination.page = newPage;
  fetchUsers();
};

// 处理分页大小变化
const handleSizeChange = (newSize: number) => {
  pagination.size = newSize;
  pagination.page = 1; // 重置到第一页
  fetchUsers();
};

// 页面加载时获取用户数据
onMounted(() => {
  fetchUsers();
});
</script>
  
<style scoped>
.dialog-footer {
  text-align: right;
}

.el-table .el-button {
  margin-left: 8px;
}

.el-table .el-button:first-child {
  margin-left: 0;
}

.el-dialog .el-input,
.el-dialog .el-input-number {
  width: 100%;
}
</style>
  